package com.rp.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 通用文件下载组件
 * @author HuangJian
 *
 */
public class DownloadComponent {
	
	private static Logger log = Logger.getLogger(DownloadComponent.class);
	
	private static final String CONTENT_TYPE = "application/octet-stream";
	
	@SuppressWarnings("unused")
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public DownloadComponent(){}
	
	/**
	 * 带参数的构造函数
	 * @param request
	 * @param response
	 */
	public DownloadComponent(HttpServletRequest request, HttpServletResponse response){
		this.request = request;
		this.response = response;
	}
	
	/**
	 * 文件下载
	 * @param absolutePath 文件的绝对路径
	 * @param filename 指定下载后的文件名
	 * @throws IOException
	 */
	public void downloadFile(String absolutePath, String filename) throws IOException{
		
		if(this.response == null){
			log.error("response is null! Please to instantiate it!");
		}else{
			BufferedInputStream bis = null;  
	        BufferedOutputStream bos = null; 
	        
	        File file = new File(absolutePath); 
	  
	        response.setContentType(CONTENT_TYPE);
	        response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(filename.getBytes("gbk"), "iso8859-1"));
			response.addHeader("Content-Length", "" + file.length());
	  
	        bis = new BufferedInputStream(new FileInputStream(absolutePath));  
	        bos = new BufferedOutputStream(response.getOutputStream());  
	        byte[] buff = new byte[2048];  
	        int bytesRead;  
	        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
	            bos.write(buff, 0, bytesRead);  
	        }  
	        bis.close();  
	        bos.close();
		}
		
	}
	
	
	
}
